<template>
  <view class="activity-popup" :class="visible ? 'show' : 'hide'" @tap.stop>
    <view class="popup-mask" @click="closePopup"></view>
    <view class="popup-inner">
      <view class="poster" hover-class="hovering" :class="{ loaded: imageLoaded }" @click="onPosterClick">
        <image
          v-show="!imageLoaded"
          class="placeholder-img"
          mode="aspectFit"
          src="/static/home/activity/PlaceHolder.png"
        />
        <image v-show="imageLoaded" class="poster-img" mode="aspectFit" :src="posterImage" @load="onPosterLoad" />
      </view>
      <view class="close-btn" hover-class="hovering" @click="closePopup">
        <image class="close-icon" mode="aspectFit" src="/static/home/activity/Dismiss.png" />
      </view>
    </view>
    <Modal :visible="showSettingError" :title="$t('APP.Common.BoolthTips.Text')" @ok="openSettings" ok-text="去打开">
      <view class="model-tips system-modal">{{ $t('APP.Common.BoolthTips.TitleTips.Text') }}</view>
      <image :src="showSettingPic" style="width: 100%" mode="aspectFit"></image>
    </Modal>
    <Modal
      :visible="showLocationErrorPic ? true : false"
      :title="$t('APP.Pairing.Error.Android.WXMPLocation.Text')"
      @ok="showLocationErrorPic = ''"
      ok-text="知道了"
    >
      <image :src="showLocationErrorPic" style="width: 100%" mode="aspectFit"></image>
    </Modal>
  </view>
</template>

<script setup lang="ts">
import { getPortalPage, PortalActivityJumpTypes, type ApplianceType, type PortalActivity } from '@/api/content'
import netconfig from '@/config/netconfig'
import Modal from '@/common/modal.vue'
import { safeTrack } from '@/dataReport/dataReportUtil'
import { trackEvent, TrackType } from '@/dataReport/tracks'
import { actionDebounce, toPage, checkReason } from '@/utils/mpHelper'
import { useApplianceMethods } from './useApplianceMethods'
import { useI18n } from 'vue-i18n'
import {
  checkLocationPermission,
  OS_SYSTEM_LOCATION_PERMISSION,
  APPLICATION_LOCATION_PERMISSION,
  WXMP_LOCATION_PERMISSION,
} from '@/utils/basicHelper'
import { useEnvStore } from '@/store/env'
import { useAuthStore } from '@/store/auth'
const i18n = useI18n()
const envStore = useEnvStore()
const authStore = useAuthStore()
const plantFrom = computed(() => envStore.systemInfo.platform)
const props = defineProps<{
  visible: boolean
  appliance?: ApplianceType[] | null
}>()

const emit = defineEmits<{
  (e: 'open'): void
  (e: 'close'): void
  (e: 'update:visible', visible: boolean): void
}>()
defineExpose({
  loadData,
})

const { addAppliance } = useApplianceMethods()

const activityData = ref<PortalActivity | null>(null)
const imageLoaded = ref(false)
const posterImage = computed(() => {
  if (activityData.value) {
    return netconfig.ASSETSPRE + activityData.value?.imgUrl
  }
  return ''
})

function openPopup() {
  emit('open')
  emit('update:visible', true)
}
function closePopup() {
  emit('close')
  emit('update:visible', false)
}
function openSettings() {
  uni.openSetting({
    success: (res) => {
      console.error(res)
    },
  })
}
async function loadData(appliances?: ApplianceType[]): Promise<void> {
  activityData.value = null
  const res = await getPortalPage(appliances ? appliances : null)
  //未登录态时根据缓存判断是否展示活动弹框
  if (!authStore.isLogin) {
    const posterData: PortalActivity = uni.getStorageSync('PortalActivityCacheKey')
    const timeStamp = new Date().toLocaleDateString()
    if (
      posterData.id === res?.data?.id &&
      posterData.description === res?.data?.description &&
      timeStamp == posterData.hasShowTime
    ) {
      return
    }
  }
  activityData.value = res.data
  if (!activityData.value) return
  imageLoaded.value = false
  openPopup()
}

function onPosterLoad() {
  imageLoaded.value = true
  if (authStore.isLogin) {
    return
  }
  updatePosterCacheData(activityData.value?.id as number, activityData.value?.description as string)
}
function updatePosterCacheData(id: number, posterDescription: string) {
  const posterData: PortalActivity = {
    id: id,
    description: posterDescription,
    hasShowTime: new Date().toLocaleDateString(),
  }
  uni.setStorageSync('PortalActivityCacheKey', posterData)
}
const showSettingPic = ref('')
const showSettingError = ref(false)
const showLocationErrorPic = ref('')
const onPosterClick = actionDebounce({
  call: async () => {
    if (!activityData.value) return
    let hasAppliance = false
    if (!authStore.isLogin) {
      hasAppliance = false
    } else {
      if (props.appliance) {
        props.appliance?.length > 0 ? (hasAppliance = true) : (hasAppliance = false)
      }
    }
    trackEvent(
      'click_opening_screen',
      { opening_screen_id: activityData.value.id || '', hasAppliance },
      TrackType.BusinesssScene
    )
    switch (activityData.value.jumpType) {
      case PortalActivityJumpTypes.WechatArticle: {
        return toPage('/pages/webview/webview', {
          url: activityData.value.landingPage,
        })
      }
      case PortalActivityJumpTypes.AddAppliance: {
        const checkSetting = await checkReason()
        if (!checkSetting) {
          return
        } else if (checkSetting != true && checkSetting.indexOf('.jpg')) {
          showSettingPic.value = checkSetting
          return (showSettingError.value = true)
        }
        // 位置判断
        try {
          await checkLocationPermission()
        } catch (error: any) {
          if (!error.Location) return
          if (error.Location === OS_SYSTEM_LOCATION_PERMISSION) {
            if (plantFrom.value === 'ios') {
              return (showLocationErrorPic.value = `${netconfig.ASSETSPRE}/Assets/icons/img_pop_Location_iOS2.png`) //蓝牙使用判断
            } else {
              return uni.showModal({
                title: i18n.t('LocationPermission.System.Dialog.Title.Text'),
                content: i18n.t('LocationPermission.System.Pairing.Dialog.Text'),
              })
            } //蓝牙使用判断
          } else if (error.Location === APPLICATION_LOCATION_PERMISSION) {
            if (plantFrom.value === 'ios') {
              return (showLocationErrorPic.value = `${netconfig.ASSETSPRE}/Assets/icons/img_pop_Location_iOS.png`) //蓝牙使用判断
            } else {
              return (showLocationErrorPic.value = `${netconfig.ASSETSPRE}/Assets/icons/img_pop_Location_Android.png`) //蓝牙使用判断
            }
          } else if (error.Location === WXMP_LOCATION_PERMISSION) {
            return uni.showModal({
              title: i18n.t('LocationPermission.WXMP_LOCATION_PERMISSION.title.text'),
              content: i18n.t('LocationPermission.WXMP_LOCATION_PERMISSION.text'),
              confirmText: i18n.t('APP.Common.GoToAuthorization.Text'),
              success: (res) => {
                if (res.confirm) {
                  openSettings()
                } else if (res.cancel) {
                  console.log('cancel...')
                }
              },
            })
          }
        }
        return addAppliance()
      }
    }
  },
  finally: () => closePopup(),
})
</script>

<style lang="less">
.activity-popup {
  display: none;
  &.show {
    display: block;
  }
  .popup-mask {
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background-color: rgba(0, 0, 0, 0.4);
    z-index: 20;
  }
  .popup-inner {
    position: fixed;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    z-index: 21;
  }
  .poster {
    width: 630rpx;
    height: 1000rpx;
    &.hovering .poster-img {
      filter: brightness(0.9);
    }
    .placeholder-img,
    .poster-img {
      width: 100%;
      height: 100%;
    }
  }
  .close-btn {
    display: flex;
    justify-content: center;
    align-items: center;
    margin-top: 40rpx;
    &.hovering {
      filter: brightness(0.9);
    }
  }
  .close-icon {
    width: 56rpx;
    height: 56rpx;
  }
}
</style>
